<template>
  <div class="product-add-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>{{ isEdit ? '编辑商品' : '新增商品' }}</h3>
          <div class="header-actions">
            <el-button @click="handleCancel">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
              <el-icon><Check /></el-icon>
              保存
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
        class="product-form"
      >
        <el-divider content-position="left">基本信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编码" prop="code">
              <el-input v-model="productForm.code" placeholder="请输入商品编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="productForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option label="电子产品" value="电子产品" />
                <el-option label="服装鞋帽" value="服装鞋帽" />
                <el-option label="家居用品" value="家居用品" />
                <el-option label="食品饮料" value="食品饮料" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="productForm.unit" placeholder="请选择单位" style="width: 100%">
                <el-option label="个" value="个" />
                <el-option label="台" value="台" />
                <el-option label="件" value="件" />
                <el-option label="套" value="套" />
                <el-option label="盒" value="盒" />
                <el-option label="包" value="包" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="规格" prop="specification">
          <el-input v-model="productForm.specification" placeholder="请输入商品规格" style="width: 50%" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购价" prop="purchasePrice">
              <el-input-number 
                v-model="productForm.purchasePrice" 
                :min="0" 
                :precision="2"
                style="width: 100%"
                placeholder="请输入采购价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售价" prop="salePrice">
              <el-input-number 
                v-model="productForm.salePrice" 
                :min="0" 
                :precision="2"
                style="width: 100%"
                placeholder="请输入销售价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="库存" prop="stock">
          <el-input-number 
            v-model="productForm.stock" 
            :min="0"
            style="width: 200px"
            placeholder="请输入库存数量"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="image-uploader"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            action="#"
          >
            <el-image
              v-if="productForm.image"
              :src="productForm.image"
              class="uploaded-image"
              fit="cover"
            />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入商品描述"
            style="width: 50%"
          />
        </el-form-item>

        <el-divider content-position="left">SKU配置</el-divider>

        <el-form-item label="启用SKU">
          <el-switch v-model="skuEnabled" active-text="启用" inactive-text="关闭" />
        </el-form-item>

        <div v-if="skuEnabled" class="sku-config">
          <div
            v-for="(attr, index) in skuAttributes"
            :key="index"
            class="attribute-config"
          >
            <div class="attr-header">
              <h4>属性 {{ index + 1 }}</h4>
              <el-button type="danger" size="small" text @click="handleRemoveAttribute(index)">
                删除
              </el-button>
            </div>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="属性名称">
                  <el-input v-model="attr.name" placeholder="如：颜色、尺码" />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="属性值">
                  <el-tag
                    v-for="(value, vIndex) in attr.values"
                    :key="vIndex"
                    closable
                    @close="handleRemoveValue(index, vIndex)"
                    style="margin-right: 10px"
                  >
                    {{ value }}
                  </el-tag>
                  <el-input
                    v-model="attr.newValue"
                    placeholder="输入后回车添加"
                    style="width: 200px"
                    @keyup.enter="handleAddValue(index)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-button type="primary" plain @click="handleAddAttribute">
            <el-icon><Plus /></el-icon>
            添加属性
          </el-button>

          <el-divider />

          <el-alert
            v-if="skuCombinationCount > 0"
            :title="`将生成 ${skuCombinationCount} 个SKU`"
            type="info"
            :closable="false"
            style="margin-bottom: 10px"
          />

          <div class="sku-actions" style="margin-bottom: 10px">
            <el-button type="primary" @click="generateSKUs">
              <el-icon><Plus /></el-icon>
              生成SKU
            </el-button>
          </div>

          <el-table v-if="generatedSKUs.length" :data="generatedSKUs" stripe style="margin-top: 10px">
            <el-table-column prop="skuCode" label="SKU编码" width="160" />
            <el-table-column label="规格组合" min-width="200">
              <template #default="{ row }">
                <el-tag
                  v-for="(value, key) in row.specifications"
                  :key="key"
                  size="small"
                  style="margin-right: 5px"
                >
                  {{ key }}:{{ value }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="价格" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.price"
                  :min="0"
                  :precision="2"
                  size="small"
                  style="width: 120px"
                />
              </template>
            </el-table-column>
            <el-table-column label="库存" width="120">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.stock"
                  :min="0"
                  size="small"
                  style="width: 100px"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Check, Close } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const submitLoading = ref(false)
const productFormRef = ref()

// 判断是否为编辑模式
const isEdit = computed(() => !!route.query.id)

const productForm = reactive({
  code: '',
  name: '',
  category: '',
  specification: '',
  unit: '',
  purchasePrice: 0,
  salePrice: 0,
  stock: 0,
  status: '启用',
  image: '',
  description: ''
})

const productRules = {
  code: [
    { required: true, message: '请输入商品编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购价', trigger: 'blur' }
  ],
  salePrice: [
    { required: true, message: '请输入销售价', trigger: 'blur' }
  ]
}

// SKU相关状态与方法
const skuEnabled = ref(false)
const skuAttributes = ref([{ name: '', values: [], newValue: '' }])
const generatedSKUs = ref([])

const skuCombinationCount = computed(() => {
  const validAttrs = skuAttributes.value.filter(attr => attr.name && attr.values.length > 0)
  if (validAttrs.length === 0) return 0
  return validAttrs.reduce((count, attr) => count * attr.values.length, 1)
})

const handleAddAttribute = () => {
  skuAttributes.value.push({ name: '', values: [], newValue: '' })
}

const handleRemoveAttribute = (index) => {
  skuAttributes.value.splice(index, 1)
}

const handleAddValue = (index) => {
  const attr = skuAttributes.value[index]
  if (attr.newValue && attr.newValue.trim()) {
    attr.values.push(attr.newValue.trim())
    attr.newValue = ''
  }
}

const handleRemoveValue = (attrIndex, valueIndex) => {
  skuAttributes.value[attrIndex].values.splice(valueIndex, 1)
}

const cartesianProduct = (arrays) => {
  return arrays.reduce((acc, array) => {
    return acc.flatMap(x => array.map(y => [...x, y]))
  }, [[]])
}

const generateSKUs = () => {
  const validAttrs = skuAttributes.value.filter(attr => attr.name && attr.values.length > 0)
  if (validAttrs.length === 0) {
    ElMessage.warning('请至少配置一个属性')
    return
  }
  if (!productForm.code) {
    ElMessage.warning('请先填写商品编码')
    return
  }

  const combinations = cartesianProduct(validAttrs.map(attr => 
    attr.values.map(value => ({ name: attr.name, value }))
  ))

  generatedSKUs.value = combinations.map((combo) => {
    const specs = {}
    let skuCode = `${productForm.code}-`

    combo.forEach((item, i) => {
      specs[item.name] = item.value
      skuCode += item.value.substring(0, 3).toUpperCase()
      if (i < combo.length - 1) skuCode += '-'
    })

    return {
      skuCode,
      specifications: specs,
      price: Number(productForm.salePrice) || 0,
      stock: 0
    }
  })
}

const handleImageSuccess = (response, file) => {
  productForm.image = URL.createObjectURL(file.raw)
  ElMessage.success('图片上传成功')
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleCancel = () => {
  router.push({ name: 'ProductsList' })
}

const handleSubmit = async () => {
  if (!productFormRef.value) return

  try {
    await productFormRef.value.validate()

    // 若启用SKU，需确保已生成SKU
    if (skuEnabled.value && generatedSKUs.value.length === 0) {
      ElMessage.warning('请先生成SKU')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    let totalStock = productForm.stock
    let skus = []
    let attrs = []

    if (skuEnabled.value) {
      attrs = skuAttributes.value
        .filter(attr => attr.name)
        .map(attr => ({ name: attr.name, values: attr.values.slice() }))

      skus = generatedSKUs.value.map(sku => ({
        skuCode: sku.skuCode,
        specifications: sku.specifications,
        price: Number(sku.price) || 0,
        stock: Number(sku.stock) || 0,
        status: true
      }))

      totalStock = skus.reduce((sum, s) => sum + Number(s.stock || 0), 0)
    }

    const productData = {
      ...productForm,
      stock: totalStock,
      skuEnabled: skuEnabled.value,
      skuAttributes: attrs,
      skus,
      skuCount: skus.length
    }

    if (isEdit.value) {
      // 编辑模式
      productData.id = route.query.id
      ElMessage.success('编辑商品成功')
    } else {
      // 新增模式
      productData.id = Date.now()
      productData.createTime = new Date().toLocaleString()
      ElMessage.success('新增商品成功')
    }

    router.push({ name: 'ProductsList' })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 加载商品数据（编辑模式）
const loadProductData = async () => {
  if (!isEdit.value) return
  
  try {
    // 模拟API调用加载商品数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 这里应该从后端加载数据，现在使用模拟数据
    const mockData = {
      code: 'P' + route.query.id,
      name: '示例商品',
      category: '电子产品',
      specification: '标准版',
      unit: '个',
      purchasePrice: 100,
      salePrice: 150,
      stock: 100,
      status: '启用',
      image: '',
      description: '这是一个示例商品'
    }
    
    Object.assign(productForm, mockData)
    ElMessage.success('商品数据加载成功')
  } catch (error) {
    ElMessage.error('加载商品数据失败')
  }
}

onMounted(() => {
  loadProductData()
})
</script>

<style scoped>
.product-add-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.product-form {
  max-width: 1200px;
}

.attribute-config {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 12px;
}

.attr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.attr-header h4 {
  margin: 0;
  color: #303133;
  font-size: 14px;
}

.sku-config {
  padding: 10px 0;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.uploaded-image {
  width: 150px;
  height: 150px;
  display: block;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>

